<script setup>
import { useApi } from "../../composables/useApi"
import showTost from "@/components/toast/index.js"
import * as XLSX from "xlsx"
import { storeToRefs } from "pinia"
import { useAppStore } from "../../store/app"
import moment from "moment"
import platformGrade from "@/api/platform.grade"

const appStore = useAppStore()

const { nationArr, sexArr } = storeToRefs(appStore)
import { reactive, ref } from "vue"
import TeatherRightDrawaer from "@/pages/platform/components/teatherRightDrawaer.vue"
import GradeRightDrawear from "@/pages/platform/components/gradeRightDrawear.vue"
import GradeHeader from "@/pages/platform/components/gradeHeader.vue"
import Toast from "@/components/toast/Toast"
import { pl } from "element-plus/es/locale/index.mjs"
//基本数据list
let list = ref([])
let page = ref(1)
let limit = ref(20)
let total = ref(0) //总数
let isAdd = ref(false)
const selected = ref([])
let queryFrom = ref({
  page: 1,
  limit: 20,
  realName: "",
  sex: "",
  nation: "",
  birthTime: "",
  entryTime: "",
})

const headers = [
  {
    title: "年级名称",
    key: "title",
    width: "240px",
    align: "start",
  },
  {
    title: "年级主任",
    width: "240px",
    align: "start",
    key: "teacher_name",
  },
  {
    title: "班级数量",
    width: "240px",
    align: "start",
    key: "classNum",
  },
  {
    title: "学生人数",
    width: "240px",
    align: "start",
    key: "studentNum",
  },
  {
    title: "操作",
    align: "end",
    sortable: false,
    key: "options",
  },
]

const getList = async () => {
  const { data } = await platformGrade.getList(queryFrom.value)
  console.log(data)
  total.value = data.value.data.total
  list.value = data.value.data.data.map((item) => {
    return {
      ...item,
      id: item.grade_id,
    }
  })
  console.log(list.value)
}

const dialogFlag = ref(false)
// 头部表单回调
const onChange = (val) => {
  let data = JSON.parse(JSON.stringify(val))
  console.log(data)
  data.birthTime = [data.birthStartTime, data.birthEndTime]
  data.entryTime = [data.entryStartTtime, data.entryEndTime]
  queryFrom.value = { ...queryFrom.value, ...data }
  getList()
}
const isConfirmDialogVisible = ref(false)
// 删除确认弹窗
const onHandleDelete = async (val) => {
  Toast.error('确定要删除吗')
  let ids = val.data.map((item) => item.gradeId)
  console.log(ids)
  const { data } = await platformGrade.del(ids)
  console.log(data.value)
  if (data.value.status == 200) {
    Toast.success("删除成功")
    queryFrom.value.page = 1
    isConfirmDialogVisible.value = false
    if (val.type == "detail") {
      dialogFlag.value = false
    }
    getList()
  }
}
const selectedItems = ref([])

// 确认弹窗文本
const confirmMsg = ref("")
const currentOptionData = ref({})

// 打开删除弹窗
const onHandleDialog = (type) => {
  if (type == "delete") {
    console.log(selectedItems)
    if (selectedItems.value.length == 0) return
    let data = list.value.filter((item) =>
      selectedItems.value.find((val) => val == item.id),
    )
    console.log(data)
    currentOptionData.value = {
      data: data,
      type: "list",
    }
    confirmMsg.value = `确认删除${data
      .map((item) => item.title)
      .toString()}的信息吗?`
    isConfirmDialogVisible.value = true
  } else {
    addDialogFlag.value = true
  }
}
// 详情数据
const detailData = ref({})
const viewDetail = async (item) => {
  console.log(item)
  const { data } = await platformGrade.info(item.gradeId)
  console.log(data)
  detailData.value = data.value.data
  dialogFlag.value = true
}
// 添加教师弹窗falg
const addDialogFlag = ref(false)
const refVForm = ref()

// 下载模板
const downLoadTemplate = async () => {
  const { data } = await useApi("/admin/Base/downFile").post({ type: 1 })
  console.log(data.value)
  if (data.value.status == 200) {
    const link = document.createElement("a")
    link.href = data.value.data.fileUrl
    link.download = data.value.data.fileName
    link.target = "_blank" // 可选，如果希望在新窗口中下载文件，请取消注释此行
    link.click()
  }
}
// 新增取消回调
const resetForm = () => {
  refVForm.value?.reset()
  addDialogFlag.value = false
}

const valid = ref(false)
const form = reactive({
  title: "", //班级名称
  teacher_name: "", //年级主任
})
const confirmAddTeacher = async (args) => {
  if (!valid.value) return
  const { data } = await platformGrade.add(form)
  if (data.value.status == 200) {
    refVForm.value?.reset()
    addDialogFlag.value = false
    Toast.success("新增成功")
    queryFrom.value.page = 1
    getList()
  } else {
    console.log(data.value.msg)
    // showTost("新增成功", {duration: 3000, type: "success"})
    Toast.error(data.value.msg)
  }
}
let sexList = ref(["男", "女"])
const onHandleEdit = () => {
  queryFrom.value.page = 1
  getList()
}
getList()
const required = (value, name) => !!value || `${name}为必填字段`

const teacherList = ref([])
const getTeacherList = async () => {
  const { data } = await useApi("/admin/Api.Teacher/indexList").post({})
  if (data.value.status == 200) {
    teacherList.value = data.value.data
  }
}
getTeacherList()
const import_page = ref(1)
const import_limit = ref(10)
const import_percent = ref(0)
const loading = ref(false)

const partPost = async (tableData) => {
  let perdata = []
  for (
    let i = (import_page.value - 1) * import_limit.value;
    i < import_page.value * import_limit.value;
    i++
  ) {
    if (tableData[i]) {
      perdata.push(tableData[i])
    }
  }
  let total_page = Math.ceil(tableData.length / import_limit.value)
  import_percent.value = Math.ceil((import_page.value * 100) / total_page)
  loading.value = true
  console.log(perdata)
  const { data } = await useApi("/admin/Api.Teacher/upload").post(
    JSON.stringify(perdata),
  )
  if (data.value.status == 200) {
    if (import_page.value <= total_page - 1) {
      import_page.value = import_page.value + 1
      partPost(data)
    } else {
      // this.dialog.importDialogstatus = false;
      showTost("导入完成", { duration: 3000, type: "success" })
      loading.value = false
    }
  }
}

const onChangePage = (val) => {
  queryFrom.value.page = val.page
  queryFrom.value.limit = val.limit
  getList()
}
const drawaerDelete = async (val) => {
  console.log(val)
  currentOptionData.value = {
    data: [val],
    type: "detail",
  }
  confirmMsg.value = `确认删除${val.title}的信息吗`
  isConfirmDialogVisible.value = true
}
const viewDetailClassStudent = (type, item) => {
  showTost("暂未开放")
  if (type == "class") {
  }
}
</script>

<template>
  <div class="content">
    <grade-right-drawear
      @onHandleDelete="drawaerDelete"
      :teacherList="teacherList"
      @onHandleEdit="onHandleEdit"
      :detailData="detailData"
      @update:isDrawerOpen="dialogFlag = $event"
      :is-drawer-open="dialogFlag"
    ></grade-right-drawear>

    <ConfirmDialog
      :handleData="currentOptionData"
      v-model:isDialogVisible="isConfirmDialogVisible"
      @confirm="onHandleDelete"
      :confirm-msg="confirmMsg"
      :confirmation-question="confirmMsg"
      cancel-msg="Unsubscription Cancelled!!"
    />
    <!-- 头部 -->
    <grade-header
      title="年级信息"
      button-text="添加年级"
      @onChange="onChange"
      @onHandle="onHandleDialog"
    />
    <VDataTable
      v-model="selectedItems"
      :headers="headers"
      :items="list"
      :items-per-page="100"
      item-key="id"
      show-select
      class="text-no-wrap"
    >
      <template #item.options="{ item }">
        <div class="d-flex align-center options-right-display">
          <div
            @click="viewDetailClassStudent(item, 'class')"
            class="me-4 cursor-pointer"
          >
            查看班级
          </div>
          <div
            @click="viewDetailClassStudent(item, 'student')"
            class="me-4 cursor-pointer"
          >
            查看学生
          </div>
          <div class="d-flex flex-column ms-3 cursor-pointer">
            <i @click="viewDetail(item)" class="ri-menu-line"></i>
          </div>
        </div>
      </template>
    </VDataTable>
    <PaginationVue
      @onChange="onChangePage"
      :current-page="queryFrom.page"
      :page-size="queryFrom.limit"
      :total="total"
    />

    <!--    添加对话框-->
    <VDialog
      class="header-box"
      :persistent="true"
      max-width="600"
      :model-value="addDialogFlag"
    >
      <div style="width: 600px" class="dialog-body">
        <AppDrawerHeaderSection
          title="添加年级"
          @cancel="addDialogFlag = false"
        />
        <VDivider/>
        <VCard>
          <PerfectScrollbar :options="{ wheelPropagation: false }" class="h-60">
            <VCardText>
              <VForm
                v-model="valid"
                ref="refVForm"
                @submit.prevent="confirmAddTeacher"
              >
                <VRow>
                  <VCol cols="6">
                    <VTextField
                      v-model="form.title"
                      label="年级名称"
                      :rules="[(val) => required(val, '班级姓名')]"
                      placeholder="请输入班级姓名"
                    >
                      <template v-slot:label>
                        <span>年级名称</span>
                        <span style="color: red; margin-left: 4px">*</span>
                      </template>
                    </VTextField>
                  </VCol>
                  <VCol cols="6">
                    <v-autocomplete
                      v-model="form.teacher_id"
                      :items="teacherList"
                      item-title="real_name"
                      item-value="teacher_id"
                      label="年级主任"
                      :rules="[(val) => required(val, '年级主任')]"
                      class="input-width-height"
                    >
                      <template v-slot:label>
                        <span>年级主任</span>
                        <span style="color: red; margin-left: 4px">*</span>
                      </template>
                    </v-autocomplete>
                  </VCol>
                  <VCol cols="12">
                    <div class="d-flex justify-end">
                      <VBtn
                        style="border: 1px solid #8a8d93"
                        color="secondary"
                        type="reset"
                        variant="tonal"
                        class="me-4"
                        @click="resetForm"
                      >
                        取消
                      </VBtn>
                      <VBtn type="submit" color="primary" class="me-4">
                        添加
                      </VBtn>
                    </div>
                  </VCol>
                </VRow>
              </VForm>
            </VCardText>
          </PerfectScrollbar>
        </VCard>
      </div>
    </VDialog>
  </div>
</template>

<style lang="scss" scoped>
.header-box {
  background-color:transparent  !important;
}
</style>
